/**
 * ------------------------------------------------------
 *  学生信息新增/编辑页
 * ------------------------------------------------------
 *
 * Note: .默认为新增学生信息，通过url参数id指定studentId时为编辑学生信息
 *
 */
import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select,
    message,
    Col,
    Row,
    DatePicker
  } from 'antd'
  import { PlusOutlined } from '@ant-design/icons'
  import { Link, useNavigate, useSearchParams } from 'react-router-dom'
  import './index.scss'
import {  useEffect, useState } from 'react'
import { createStudentAPI, getStudentById, updateStudentAPI } from '@/apis/student'
import { useClasses } from '@/hooks/useClasses'
import zhCN from 'antd/lib/date-picker/locale/zh_CN';
import dayjs from 'dayjs'
import { UploadRequest, verImage } from '@/utils/helper'
import { UPLOAD_API } from '@/config/constants'

  
  const { Option } = Select
  const { TextArea } = Input;
  const Publish = () => {
    const navigate = useNavigate()
    const [messageApi,contextHolder] = message.useMessage();
    // 获取班级列表
    const {classesList} = useClasses()
    // 提交表单
    const onFinish = (formValue) => {
      const { fullname, gender, moreinfo, classesid,studentid,brithday,mobile,address } = formValue
      //根据接口要求处理表单项
      const reqData = {
        fullname,
        moreinfo,
        gender,
        studentid,
        brithday:dayjs(brithday).unix(),
        mobile,
        address,
        cover: {
          images: imageList.map(item => {
            if (item.response) {
              return item.response.data.url
            } else {
              return item.url
            }
          })
        },
        classesid
      }
    // 调用接口提交
      if (studentId) {
        // 更新接口
        updateStudentAPI({ ...reqData, id: studentId })
        messageApi.success(`编辑成功`)
      } else {
        // 新增接口
        createStudentAPI(reqData)
        messageApi.success(`新增成功`,1,()=>{
            navigate('/student')
        })
      }

    }
  
    //验证上传图片格式
    function beforeUpload(file){
      const res = verImage(file)
      if(res===true){
        return res
      }
      messageApi.error(res)
      return false
    }

    // 上传照片回调
    const [imageList,setImageList] = useState([])
    const onChange = (value) => {
      setImageList(value.fileList)
    }
   
    // 编辑学生信息时回填数据
    const [searchParams] = useSearchParams()
    const studentId = searchParams.get('id')
    // 获取实例
    const [form] = Form.useForm()
    useEffect(()=>{
      //通过id获取数据
      async function getStudentDetail(){
        const res = await getStudentById(studentId)
        const data = res.data
        form.setFieldsValue({
          ...data,
          brithday:data.brithday > 0 ? dayjs.unix(data.brithday) : '',
        })
        //显示图片
        setImageList(data.cover.images.map(url =>{
          return {url}
        }))
      }
      //编辑时获取详细信息
      if (studentId) {
        getStudentDetail()
      }
    },[studentId,form]) 

    return (
      <div className="publish">
        <Card
          title={
            <Breadcrumb items={[
              { title: <Link to={'/'}>首页</Link> },
              { title: `${studentId ? '编辑' : '新增'}学生信息` },
            ]}
            />
          }
        >
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ gender: 1 }}
            onFinish={onFinish}
            form={form}
          >
            <Row>
              <Col span={14}>
                <Form.Item
                label="姓名"
                name="fullname"
                rules={[{ required: true, message: '请输入学生姓名' }]}
              >
                <Input placeholder="请输入学生姓名" style={{ width: 200 }} />
              </Form.Item>
              
              <Form.Item
                  label="班级"
                  name="classesid"
                  rules={[{ required: true, message: '请选择所在班级' }]}
                >
                  <Select placeholder="请选择所在班级" style={{ width: 200 }}>
                    {classesList.map(item => <Option key={item.id} value={item.id}>{item.title}</Option>)}
                  </Select>
                </Form.Item>
                <Form.Item name="gender" 
                  label="性别"
                  rules={[{ required: true, message: '请选择性别' }]}
                >
                  <Radio.Group>
                    <Radio value="1">男</Radio>
                    <Radio value="0">女</Radio>
                  </Radio.Group>
                </Form.Item>
                <Form.Item
                  hasFeedback
                  label="学号"
                  name="studentid"
                  rules={[
                    { required: true, message: '请输入学号' },
                    { pattern: /^[1-9]\d{7}$/, message: '请输入非0开头的8位数学号' }
                  ]}
                >
                <Input placeholder="请输入学号" style={{ width: 200 }} />
              </Form.Item>              
              <Form.Item label="生日" name="brithday">
                <DatePicker locale={zhCN} 
                  minDate={(dayjs().add(-20, 'year'))}
                  maxDate={dayjs().add(-6,'year')}
                />
              </Form.Item>
              </Col>
              <Col span={10}>                
                <Form.Item label="照片">
                  <Upload
                    listType="picture-card"
                    showUploadList
                    action={ UPLOAD_API }
                    name='image'
                    onChange={onChange}
                    beforeUpload={beforeUpload}
                    customRequest={UploadRequest}
                    maxCount={1}
                    fileList={imageList}
                  >
                    <div style={{ marginTop: 8 }}>
                      <PlusOutlined />
                    </div>
                  </Upload>
                </Form.Item>
                <Form.Item
                  label="手机号"
                  name="mobile"
                  rules={[
                    {
                      required: false,
                      message: '请输入手机号',
                    },
                    {
                      pattern: /^1[3-9]\d{9}$/,
                      message: '请输入正确的手机号格式'
                    }
                  ]}
                >
                  <Input placeholder="请输入手机号" />
                </Form.Item>
                <Form.Item label="地址" name="address">
                  <TextArea rows={3} placeholder="联系地址" />
                </Form.Item>
              </Col>              
            </Row>

            <Form.Item label="其他信息：" name="moreinfo" labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <TextArea rows={6}  />
            </Form.Item>
  
            <Form.Item wrapperCol={{ span: 24 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  提交
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        {contextHolder}
      </div>
    )
  }
  
  export default Publish